<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="roleList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['rowbottom', 'vcenter', i1 === 0 ? 'rowtop' : '']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  :closable="true"
                  @close="removeRightById(scope.row, item1.id)"
                >
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环嵌套渲染二级权限 -->
                <el-row
                  :class="['vcenter', i2 === 0 ? '' : 'rowtop']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      :closable="true"
                      @close="removeRightById(scope.row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      :closable="true"
                      type="info"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showUpdateRoleDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRoleById(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
              >分配角色</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色弹出框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialogVisible"
      width="50%"
      @close="addRoleDialogClosed"
    >
      <el-form
        :model="addRoleForm"
        :rules="addRoleFormRules"
        ref="addRoleFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色的弹出框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="updateRoleDialogVisible"
      width="50%"
      @close="updateRoleDialogClosed"
    >
      <el-form
        :model="updateRoleForm"
        :rules="updateRoleFormRules"
        ref="updateRoleFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="updateRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="updateRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限弹出框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="SetRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <el-tree
        :data="rightsList"
        :props="treeProps"
        :show-checkbox="true"
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="SetRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表数据
      roleList: [],
      updateRoleForm: [],
      addRoleDialogVisible: false,
      updateRoleDialogVisible: false,
      SetRightDialogVisible: false,
      //   所有权限列表
      rightsList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children',
      },
      addRoleForm: {
        roleName: '',
        roleDesc: '',
      },
      // 树形控件默认选中的id值
      defKeys: [],
      // 当前即将分配权限的id
      roleId:'',

      addRoleFormRules: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '角色名称长度在3~10个字符之间',
            trigger: 'blur',
          },
        ],
        roleDesc: [
          {
            min: 6,
            max: 20,
            message: '角色描述长度在6~20个字符之间',
            trigger: 'blur',
          },
        ],
      },

      //   修改角色的表单规则
      updateRoleFormRules: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '角色名称长度在3~10个字符之间',
            trigger: 'blur',
          },
        ],
        roleDesc: [
          {
            min: 6,
            max: 20,
            message: '角色描述长度在6~20个字符之间',
            trigger: 'blur',
          },
        ],
      },
    }
  },

  created() {
    this.getRoleList()
  },
  methods: {
    // 获取所有角色列表
    async getRoleList() {
      const { data: res } = await this.$http.get('/roles')
      if (res.meta.status !== 200)
        return this.$message.error('获取角色列表失败')
      this.roleList = res.data
    },

    // 点击按钮，添加角色
    addRole() {
      this.$refs.addRoleFormRef.validate(async (valid) => {
        if (!valid) return
        // 发起添加角色请求
        const { data: res } = await this.$http.post('/roles', {
          roleName: this.addRoleForm.roleName,
          roleDesc: this.addRoleForm.roleDesc,
        })
        if (res.meta.status !== 201) return this.$message.error('添加角色失败')
        this.getRoleList()
        this.addRoleDialogVisible = false
        this.$message.success('添加角色成功')
      })
    },

    // 点击取消按钮，表单内容重置
    addRoleDialogClosed() {
      this.$refs.addRoleFormRef.resetFields()
    },

    // 展示修改角色的弹出框
    async showUpdateRoleDialog(id) {
      const { data: res } = await this.$http.get('/roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询角色信息失败')
      }
      this.updateRoleForm = res.data
      this.updateRoleDialogVisible = true
    },
    // 重置修改角色弹出框
    updateRoleDialogClosed() {
      this.$refs.updateRoleFormRef.resetFields()
    },

    // 点击按钮,更改角色信息
    updateRole() {
      this.$refs.updateRoleFormRef.validate(async (valid) => {
        if (!valid) return
        // 发起修改角色的请求
        const { data: res } = await this.$http.put(
          '/roles/' + this.updateRoleForm.roleId,
          {
            roleName: this.updateRoleForm.roleName,
            roleDesc: this.updateRoleForm.roleDesc,
          }
        )
        if (res.meta.status !== 200)
          return this.$message.error('更新角色信息失败')

        this.getRoleList()
        this.updateRoleDialogVisible = false
        this.$message.success('更新角色信息成功')
      })
    },

    // 点击按钮，弹出删除角色的信息框
    async removeRoleById(id) {
      // 弹出询问用户是否删除数据
      const result = await this.$confirm(
        '此操作将永久删除该角色,是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancleButtonText: '取消',
          type: 'warning',
        }
      ).catch((error) => error)

      if (result !== 'confirm') return this.$message.info('已取消删除')

      const { data: res } = await this.$http.delete('/roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除角色失败')
      this.getRoleList()
      this.$message.success('删除角色成功')
    },

    // 删除标签触发的事件
    async removeRightById(role, rightId) {
      // 弹框提示用户是否要删除
      const result = await this.$confirm(
        '此操作将删除该角色权限,是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancleButtonText: '取消',
          type: 'warning',
        }
      ).catch((error) => error)
      if (result !== 'confirm') return this.$message.info('已取消删除')
      console.log(result)
      console.log(role)
      console.log(rightId)
      const { data: res } = await this.$http.delete(
        `/roles/${role.id}/rights/${rightId}`
      ) //会返回当前角色最新的权限数据
      if (res.meta.status !== 200) return this.$message.error('删除权限失败')
      role.children = res.data
      this.$message.success('删除权限成功')
    },

    // 点击按钮，展示分配权限的弹出框
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 获取所有权限列表
      const { data: res } = await this.$http.get('/rights/tree')
      if (res.meta.status !== 200)
        return this.$message.error('获取权限列表失败')
      this.rightsList = res.data
      this.getKeys(role, this.defKeys)
      this.SetRightDialogVisible = true
    },

    // 通过递归方法循环获取三级权限的id值
    getKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getKeys(item, arr)
      })
    },
    setRightDialogClosed() {
      this.defKeys = []
    },

    // 点击按钮，为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      const str = keys.toString()
      console.log(keys)

      const {data:res} = await this.$http.post(`/roles/${this.roleId}/rights`,{rids:str})
      if(res.meta.status !== 200) return this.$message.error('分配权限失败')
      this.getRoleList()
      this.SetRightDialogVisible = false
      this.$message.success('分配权限成功')
    },
  },
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 10px;
}
.rowtop {
  border-top: 1px solid #eee;
}
.rowbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>